﻿
using ST.Torch.WebApi.Application.System.Dtos;
using ST.Torch.WebApi.Application.System.Services;
using ST.Torch.WebApi.Core.Manage;
using Microsoft.AspNetCore.Http.HttpResults;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Furion.HttpRemote;

namespace ST.Torch.WebApi.Application.System
{
    /// <summary>
    /// 文件系统
    /// </summary>
    // [AllowAnonymous]
    [ApiDescriptionSettings("File")]
    [AppAuthorize]
    public class FileAppService : IDynamicApiController
    {
        private readonly FileService _fileService;
        private IHttpContextAccessor _httpContextAccessor;
       

        public FileAppService(
             FileService fileService
            , IHttpContextAccessor httpContextAccessor
            )
        {
            _fileService = fileService;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取文件目录
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public List<FileMenu> GetFileMenu([FromForm] FileMenuReq req)
        {
            return _fileService.GetFileMenu(req.directory, req.order, req.sort);
        }
        /// <summary>
        /// 预览
        /// </summary>
        /// <param name="pathUrl"></param>
        /// <returns></returns>
        [NonUnify, HttpGet, AllowAnonymous]
        public async Task<IActionResult> Attachment([FromQuery]string pathUrl)
        {
            pathUrl = HttpUtility.UrlDecode(pathUrl, Encoding.UTF8);
            // 根据 resourceId 查询 byte[] 字节数组和 content-type
            // 返回 FileContentResult 类型

            //string filePath = Path.Combine(rootPath, req.FilePath);
            //string name = HttpUtility.UrlEncode(Request["stuName"], Encoding.UTF8);
            string filePath = _fileService.rootPath + pathUrl;

            byte[] bytes = await _fileService.ReadFileByte(pathUrl);

            return new FileContentResult(bytes, "application/octet-stream");
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpGet, NonUnify]
        public async Task<FileContentResult> FileDownloadByte([FromQuery] FileDownloadReq req)
        {

            //string rootPath = _fileService.GetRootPath();
            req.FilePath = HttpUtility.UrlDecode(req.FilePath);
            //string filePath = Path.Combine(rootPath, req.FilePath);
            string filePath = HttpUtility.UrlDecode(_fileService.rootPath + req.FilePath, Encoding.UTF8);
            byte[] bytes = await _fileService.ReadFileByte(req.FilePath);
            string Text = await _fileService.ReadFileContent(req.FilePath);
            _httpContextAccessor.HttpContext.Response.Headers.Add("Content-Disposition", $"attachment; filename={req.FileName}");
            _httpContextAccessor.HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

            //return new FileStreamResult(new MemoryStream(bytes), "application/octet-stream")
            return new FileContentResult(bytes, "application/octet-stream")
            {
                FileDownloadName = req.FileName // 配置文件下载显示名
            };
        }



        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public void DeleteBatch(List<string> req)
        {

            foreach (var path in req)
            {
                _fileService.DeleteFile(path);
            }
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public void CreateDirectory(string req)
        {


            _fileService.CreateDirectory(req);

        }

        /// <summary>
        /// 单独上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="DirectoryName">文件夹名</param>
        /// <returns></returns>
        [HttpPost, NonUnify]
        [RequestSizeLimit(long.MaxValue)]
        public async Task<dynamic> UploadFileAsync(IFormFile file, [FromForm] string DirectoryName)
        {
            // 如：保存到网站根目录下的 uploads 目录
            //var savePath = Path.Combine(App.HostEnvironment.ContentRootPath, "uploads");
            string rootPath = _fileService.rootPath;

            // var savePath = Path.Combine(rootPath, "uploads");
            //savePath = Path.Combine(savePath, DirectoryName);
            if (DirectoryName == null)
            {
                DirectoryName = "\\";
            }
            if (!DirectoryName.StartsWith("\\"))
            {
                DirectoryName = "\\" + DirectoryName;
            }

            var savePath = rootPath + DirectoryName;
            if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
            //// 这里还可以获取文件的信息
            // var size = file.Length / 1024.0;  // 文件大小 KB
            // var clientFileName = file.FileName; // 客户端上传的文件名
            // var contentType = file.ContentType; // 获取文件 ContentType 或解析 MIME 类型
            // 避免文件名重复，采用 GUID 生成
            var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(savePath, fileName);
            // 保存到指定路径
            using (var stream = File.Create(filePath))
            {
                await file.CopyToAsync(stream);
            }
            // 在动态 API 直接返回对象即可，无需 OK 和 IActionResult
            //return Ok(new { filename });
            return new
            {
                code = 200,
                msg = "上传成功",
                data = filePath.Replace(rootPath, "")

            };
           // return ;
        }

        /// <summary>
        /// 富文本框自动上传图片
        /// </summary>
        /// <param name="images"></param>
        /// <param name="catalogue"></param>
        /// <returns></returns>
        [HttpPost, NonUnify]
        public async Task<dynamic> AutoImportEditorImage([FromForm] List<EditorAutoUploadImageDto> images, [FromForm] string catalogue)
        {
            List<EditorAutoUploadImageDto> editorAutoUploadImageDtos = new List<EditorAutoUploadImageDto>();
            if (images.Count() > 0)
            {
                string rootPath = _fileService.rootPath;
                string rootPathDir = _fileService.rootPath+"\\"+ catalogue;
                foreach (var image in images)
                {
                    EditorAutoUploadImageDto editorAutoUploadImageDto = new EditorAutoUploadImageDto();
                    string name = $"{catalogue}/{Guid.NewGuid().ToString().Replace("-", "")}.jpg";
                    //服务器图片
                    byte[] fileData = null;
                    if (image.url.Contains(ConfigData.ImgUrl))
                    {
                        editorAutoUploadImageDto.url = image.url;
                    }
                    else if (image.url.Contains("base64"))
                    {

                        fileData = Convert.FromBase64String(image.url.Split(',')[1]);
                        //var client = new OssClient(_endpoint, _accessKeyId, _accessKeySecret);
                        //using (MemoryStream stream = new MemoryStream(fileData))
                        //{
                        //    var putObjectRequest = new PutObjectRequest(bucketName, name, stream);
                        //    client.PutObject(putObjectRequest);
                        //}
                    }
                    else
                    {
                        //var contentStream = await image.url.GetAsStreamAsync();
                        var _httpRemoteService = App.GetService<IHttpRemoteService>();
                        var contentStream = await _httpRemoteService.GetAsStreamAsync(image.url);
                        //var contentStream = await image.url.();
                        // 将图片转换为 Base64 格式的字符串
                        using (var memoryStream = new MemoryStream())
                        {
                            //await contentStream.Stream.CopyToAsync(memoryStream);
                            await contentStream.CopyToAsync(memoryStream);
                            string base64String = Convert.ToBase64String(memoryStream.ToArray());
                           fileData = Convert.FromBase64String(base64String);
                            //var client = new OssClient(_endpoint, _accessKeyId, _accessKeySecret);
                            //using (MemoryStream stream = new MemoryStream(fileData))
                            //{
                            //    var putObjectRequest = new PutObjectRequest(bucketName, name, stream);
                            //    client.PutObject(putObjectRequest);
                            //}
                        }
                    }
                    if (!Directory.Exists(rootPathDir))
                    {
                        // 目录不存在，创建目录
                        Directory.CreateDirectory(rootPathDir);
                    }
                    if (string.IsNullOrEmpty(editorAutoUploadImageDto.url))
                    {
                        var file = File.Create(rootPath + "\\" + name);
                        file.Write(fileData);
                        file.Dispose();
                        editorAutoUploadImageDto.url = ConfigData.ImgUrl + name;
                    }

                    editorAutoUploadImageDto.code = 200;
                    editorAutoUploadImageDto.source = image.source;
                    editorAutoUploadImageDtos.Add(editorAutoUploadImageDto);
                }
            }
            return new { code = 200, result = editorAutoUploadImageDtos };
        }


    }

}
